<?php


class openapi_api_function_v1_register extends openapi_api_function_abstract implements openapi_api_function_interface{

    
    public function protocol(){
        return $this->apiData(true,'success');
    }

    
    public function regist($params,&$code,&$sub_msg){
        $api_member = kernel::service('business.api_verify_member');
        $res = $api_member->add($params);
        if($res['error']){
            return $this->apiData(false,null,400,$res['error']);
        }else{
            //注册成功后登陆状态
            kernel::single('base_session')->start();
            $_SESSION['account'][pam_account::get_account_type(app::get('b2c')->app_id)] = $res['member_id'];
            $_SESSION['type'] = pam_account::get_account_type(app::get('b2c')->app_id);
            $_SESSION['login_time'] = time();
            $result['member_id'] = $res['member_id'];
            $result['login_token'] = kernel::single('base_session')->sess_id();
            return $this->apiData(true,$result,200,app::get('base')->_('注册成功'));
        }
    }

    
    public function store($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            if(empty($params['member_id'])){
                return $this->apiData(false,null,400,app::get('b2c')->_('参数丢失，请登录重试'));
            }
            $member_id = $params['member_id'];
        }
        $membermdl = app::get('b2c')->model('members');
        $membermdl->update(array('seller'=>'seller'),array('member_id'=>$member_id));
        $storegrade = kernel::service('business.api_verify_storegrade')->getgrades('grade_id,grade_name');
        $obj_regions_op = kernel::service('ectools_regions_apps', array('content_path'=>'ectools_regions_operation'));
        $arealist = $obj_regions_op->getRegionById(0);
        foreach ($arealist as $key => &$area) {
            unset($area['p_region_id']);
            unset($area['ordernum']);
            unset($area['region_path']);
            unset($area['step']);
        }
        if($storegrade){
            $result['gradelist'] = $storegrade;
            $result['arealist'] = $arealist;
            return $this->apiData(true,$result,200);
        }else{
            return $this->apiData(false,array('msg'=>$this->app->_('未找到经销商层级信息')));
        }
    }

    
    public function busscope($params,&$code,&$sub_msg)
    {
        //根据经销商等级和地区得到符合条件的产品线
		$cobj = app::get('b2c')->model('goods_cat');
        $rObj = app::get('business')->model('joinrule');
        $gObj = app::get('business')->model('storegrade');
        $sObj = app::get('business')->model('storemanger');
        
        $grade_id = $params['grade_id'];
        $filter['grade_id'] = $grade_id;
        $storegrade = $gObj->dump($grade_id);
        $arr_area = explode('/',$params['area']);
        switch ($storegrade['grade_order']) {
            case '1':
                $filter['area|head'] = '';
                break;
            case '2':
                $filter['area|head'] = $arr_area[0];
                break;
            case '3':
                $filter['area|head'] = $arr_area[0].'/'.$arr_area[1];
                break;
            default:
                $filter['area|head'] = $params['area'];
                break;
        }
        $rule = $rObj->getList('*',$filter);
        if(empty($filter['area|head'])||$filter['area|head']&&empty($rule)){
            unset($filter['area|head']);
            $filter['join_type']='general';
        }else{
            $filter['join_type']='special';
        }
        $srule = $rObj->getList('*',$filter);
        $lines=array();
        switch ($storegrade['grade_order']) {
            case '1':
                break;
            case '2':
               $lfilter['area|head'] = $arr_area[0];
               break;
            case '3':
               $lfilter['area|head'] = $arr_area[0].'/'.$arr_area[1];
               break;
            default:
               $lfilter['area|head'] = $params['area'];
               break;
        }

        if($srule){
            foreach($srule as $sv){
                $regions = array_filter(explode(',',$sv['store_region']));
                foreach($regions as $region){
                    $lfilter['store_grade'] = $grade_id;
                    $lfilter['store_region|has'] = ','.$region.',';
                    $limit = $sv['num'];
                    $cat = $cobj->getRow('parent_id',array('cat_id'=>$region));
                    if($cat['parent_id'] == '0'){
                        if(!$limit || $limit > $sObj->count($lfilter)){
                            $lines[] = $region;
                        }
                    }
                }
            }
        }else{
            $lines = array();  
        }
        $business = app::get('b2c')->model('goods_cat')->getList("cat_id,cat_name",array("cat_id|in"=>$lines));
        if(empty($business)){
            return $this->apiData(false,null,400,app::get('b2c')->_('暂无可代理产品'));
        }
        foreach ($business as $key => &$cat) {
            $cat['business_id'] = $cat['cat_id'];
            $cat['name'] = $cat['cat_name'];
            unset($cat['cat_id']);
            unset($cat['cat_name']);
        }
        return $this->apiData(true,$business,200);
    }

    public function scope_save($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $sto= kernel::single("business_memberstore",$member_id);
        $sto ->process($member_id);
        if($sto->isshoper == 'true'){
            $storemanger_model = app::get('business')->model('storemanger');
            $shopinfo =  $storemanger_model->getList('*', array('store_id' => $sto->storeinfo['store_id']), 0, -1);
            $shopinfo = $shopinfo[0];
            if($shopinfo['approved'] ==1){
                return $this->apiData(false,null,400,app::get('b2c')->_('您申请的经销商正在审核或已经通过审核，请与管理中心联系！'));
            }
        }

        if($sto->isshopmember == 'true'){
            return $this->apiData(false,null,400,app::get('b2c')->_('您已是店员，请与所在店主联系！'));
        }

        if($params['store_grade'] == ''){
            return $this->apiData(false,null,400,app::get('b2c')->_('请选择一个经销商类型！'));
        }

        // 经销商手机号和申请账号时填写的手机号保持一致
        $obj_members = &app::get('b2c')->model('members');
        $member = $obj_members->getList('*', array('member_id' => $member_id));
        if($member){
          $shopinfo['tel']=$member[0]['mobile'];
        }
        $shopinfo['account_id'] = $member_id;
        if($params['store_region']){
            if (is_array($params['store_region'])) {
                $shopinfo['store_region'] = ',' . implode(",", $params['store_region']) . ',';
            } else {
                $shopinfo['store_region'] = ',' . $params['store_region'] . ',';
            } 
        }
        $shopinfo['store_grade'] = $params['store_grade'];
        $shopinfo['area'] = $params['area'];
        $shopinfo['addr'] = $params['addr'];
        $_SESSION['storeapply']['shopinfo'] = $shopinfo;
        $storegrade = app::get('business')->model('storegrade')->getList('grade_order',array('grade_id'=>$shopinfo['store_grade']));
        //根据等级判断查询上级的范围
        $arr_area = explode('/', $shopinfo['area']);
        $gradefilter = array();
        switch ($storegrade[0]['grade_order']) {
            case '0':
                break;
            case '1':
                break;
            case '2':
                break;
            case '3':
               $gradefilter['area|head'] = $arr_area[0];
               break;
            case '4':
               $gradefilter['area|head'] = $arr_area[0].'/'.$arr_area[1];
               break;
            default:
               $gradefilter['area|head'] = $shopinfo['area'];
               break;
        }
        $parent_grade = app::get('business')->model('storegrade')->getRow("parent_id",array('grade_id'=>$params['store_grade']));
        if($parent_grade['parent_id']>=0){
            $gradefilter['store_grade'] = $parent_grade['parent_id'];
        }
        $pgrade = app::get('business')->model('storemanger')->getList("store_id,store_name,store_region",$gradefilter);
        //选择的产品线
        $regionArr = explode(",", $params['store_region']);
        if($parent_grade['parent_id']>0){
            foreach ($pgrade as $k => &$sto) {
                $tmp_region = explode(",", substr($sto['store_region'],1,strlen($sto['store_region'])-2));
                unset($sto['store_region']);
                if(count($regionArr)>count(array_intersect($regionArr,$tmp_region))){
                    unset($pgrade[$k]);
                }
            }
        }
        return $this->apiData(true,array('account_id'=>$member_id,'pgrade'=>array_values($pgrade)),200,app::get('b2c')->_('可入驻，请填写信息'));
    }

    
    public function store_save($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('用户信息丢失，请重新登录'));
        }
        $this->member = $this->get_current_member();
        $storemanger_model = app::get('business')->model('storemanger');
        $storeinfo = $storemanger_model->getRow('store_id',array('account_id'=>$member_id));
        $shopinfo = $_SESSION['storeapply']['shopinfo'];
        if(!empty($storeinfo)){
            $shopinfo['store_id'] = $storeinfo['store_id'];
        }
        $shopinfo['store_idcardname'] = $params['store_idcardname'];
        $shopinfo['store_name'] = $params['store_name'];
        $shopinfo['parent_id'] = $params['parent_id'];
        $shopinfo['bank_name'] = $params['bank_name'];
        $shopinfo['bank_cardid'] = $params['bank_cardid'];
        $shopinfo['pay_password'] = $params['pay_password'];
        $shopinfo['confirm_pay_password'] = $params['confirm_pay_password'];

        $shopinfo = $this->arrContentReplace($shopinfo); 
        //修改后登录用户于当前申请用户不同时，店主错误 Add by PanF  2014-5-5
        if($shopinfo['account_id'] != $member_id){
            return $this->apiData(false,null,400,app::get('business')->_('页面信息已经超时，请重新登录。'));
        }
        // 经营范围
        if($shopinfo['store_region']){
            if (is_array($shopinfo['store_region'])) {
                $shopinfo['store_region'] = ',' . implode(",", $shopinfo['store_region']) . ',';
            } else {
                $shopinfo['store_region'] = $shopinfo['store_region'];
            } 
        }

        // 关联经销商
        if($shopinfo['associate_store']){
            if (is_array($shopinfo['associate_store'])) {
                $shopinfo['associate_store'] = ',' . implode(",", $shopinfo['associate_store']) . ',';
            } else {
                $shopinfo['associate_store'] = ',' . $shopinfo['associate_store'] . ',';
            } 
        }
        $memberinfo = app::get('b2c')->model('members')->dump($member_id,"*",array(':account@pam'=>array('*')));

        $shopinfo['shop_name'] = $this->member['uname'];
        $shopinfo['email'] = $this->member['email'];

        //申请时间
        if(empty($shopinfo['apply_time'])){
            $shopinfo['apply_time'] = time();
        }

        if ($storemanger_model->save($shopinfo)) {

            if(isset($shopinfo['pay_password']) && $shopinfo['pay_password']){
                if($shopinfo['pay_password'] == $shopinfo['confirm_pay_password']){
                    $pwd = array(
                        'member_id'=>$member_id,
                        'pay_password'=>md5($shopinfo['pay_password']),
                    );

                    if(app::get('b2c')->model('members')->save($pwd)) {
                        $pwd_msg = app::get('b2c')->_('支付密码设置成功');
                    } else {
                        $pwd_msg = app::get('b2c')->_('支付密码设置失败,审核通过后前往经销商中心设置');
                    }
                }
            }
            $sto = kernel::single("business_memberstore", $shopinfo['account_id']);
            $sto->process($shopinfo['account_id']);
            if(!is_array($sto->storeinfo)){
                $splashmsg = app::get('business')->_('开店申请提交成功');
            }
            if($splashmsg){
                return $this->apiData(true,null,200,$splashmsg.','.$pwd_msg);
            } else {
                return $this->apiData(true,null,200,app::get('business')->_('开店申请提交成功,'.$pwd_msg));
            }
        } else {
            return $this->apiData(false,null,400,app::get('business')->_('提交失败'));
        }
    }

    
    public function getjoinqualify($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('用户信息丢失，请重新登录'));
        }
        $this->member = $this->get_current_member();

        $storemanger_model = app::get('business')->model('storemanger');
        
        $accountid = $member_id;

        $shopinfo = $storemanger_model->getList('*', array('account_id' => $accountid), 0, -1);
        if(empty($shopinfo)){
            return $this->apiData(false,null,501,app::get('b2c')->_('还未提交经销商信息'));
        }
        // 经销商等级
        $obj_storegrade = app::get('business')->model('storegrade');
        $obj_qualification = app::get('business')->model('joinqualification');
        $grade_info = $obj_storegrade->dump(array('grade_id' => $shopinfo[0]['store_grade']));
        $qualification = explode(',', $grade_info['qualification']);
        foreach($qualification as $vtype){
            if($vtype){
                $tmp = $obj_qualification->dump($vtype);
                $tmp = array_merge($tmp, $storemanger_model->get_real_type($tmp['attr_type']));
                if($tmp['attr_required'] == '1') $tmp['attr_valtype'] = trim('required&&'.$tmp['attr_valtype'], '&');
                unset($tmp['width']);
                unset($tmp['height']);
                $qualification_list[] = $tmp;
            }
        }
        $result['qualification'] = $qualification_list;
        $result['store_id'] = $shopinfo[0]['store_id'];

        return $this->apiData(true,$result,200);
    }

    
    public function joinqualify($params,&$code,&$sub_msg)
    {
        $storemanger_model = app::get('business')->model('storemanger');

        $shopinfo = array();
        foreach ($params['qualify'] as $key => $item) {
            $shopinfo[$item['item_name']] = $item['item_value'];
        }
        $shopinfo['store_id'] = $params['store_id'];

        $obj_qualification = app::get('business')->model('joinqualification');
        $storeinfo = $storemanger_model->getRow('*',array('store_id'=>$params['store_id']));
        $parent_store = $storemanger_model->getRow("*",array('store_id'=>$storeinfo['parent_id']));
        $parent_account = app::get('pam')->model('account')->getRow('*',array('account_id'=>$parent_store['account_id']));
        $account_info = app::get('pam')->model('account')->getRow('*',array('account_id'=>$storeinfo['account_id']));
        if ($storemanger_model->save($shopinfo)) {
            //发送站内信
            $data['to_id'] = $parent_account['account_id'];
            $data['msg_to'] = $parent_account['login_name'];
            $data['subject'] = app::get('b2c')->_("经销商入驻申请");
            $data['comment'] = app::get('b2c')->_($account_info['login_name']."提交了经销商申请");
            $data['has_sent'] = 'true';
            $data['deal_type'] = '0';
            $data['member_id'] = $account_info['account_id'];
            $data['uname'] = $account_info['login_name'];
            kernel::single('b2c_message_msg')->send($data);
            return $this->apiData(true,null,200,app::get('business')->_('提交成功,等待审核中。。。'));
        } else {
            return $this->apiData(false,null,400,app::get('business')->_('提交失败,请稍后再试。'));
        } 
    }

    
    function arrContentReplace($array) {
        if (is_array($array)) {
            foreach($array as $key => $v) {
                $array[$key] = $this->arrContentReplace($array[$key]);
            } 
        } else {
            $array = strip_tags($array);
        } 
        return $array;
    }

}
